package archive

import (
	"gitlab.com/gitlab-org/gitaly/v14/internal/git"
	"gitlab.com/gitlab-org/gitaly/v14/internal/git/catfile"
	"gitlab.com/gitlab-org/gitaly/v14/internal/gitaly/archive"
	"gitlab.com/gitlab-org/gitaly/v14/internal/gitaly/config"
	"gitlab.com/gitlab-org/gitaly/v14/internal/gitaly/transaction"
	"gitlab.com/gitlab-org/gitaly/v14/internal/storage"
	"gitlab.com/gitlab-org/gitaly/v14/proto/go/gitalypb"
)

type server struct {
	gitalypb.UnimplementedArchiveServiceServer
	cfg            config.Cfg
	txManager      transaction.Manager
	locator        storage.Locator
	gitCmdFactory  git.CommandFactory
	catfileCache   catfile.Cache
	storageManager *archive.StorageManager
	gitOperations  *archive.GitOperations
	kafkaProducer  *KafkaProducer
}

// NewServer creates a new instance of a grpc ArchiveServer
func NewServer(
	cfg config.Cfg,
	locator storage.Locator,
	gitCmdFactory git.CommandFactory,
	txManager transaction.Manager,
	catfileCache catfile.Cache,
) gitalypb.ArchiveServiceServer {
	storageManager := archive.NewStorageManager(cfg, locator, gitCmdFactory)
	gitOperations := archive.NewGitOperations(cfg, locator, gitCmdFactory)

	// Create Kafka producer for sending archive tasks
	// TODO: 从cfg中读取这些配置，目前使用默认值
	kafkaConfig := KafkaProducerConfig{
		Brokers: []string{"localhost:9092"}, // TODO: 从配置文件中读取
		Topic:   "gitaly-archive-tasks",     // TODO: 从配置文件中读取
		Enabled: false,                      // TODO: 从配置文件中读取，默认禁用
	}

	kafkaProducer, err := NewKafkaProducer(kafkaConfig)
	if err != nil {
		// 如果Kafka不可用，记录错误但不阻止服务启动
		// 在这种情况下，只会写入元数据而不发送消息
		kafkaProducer = &KafkaProducer{enabled: false}
	}

	return &server{
		cfg:            cfg,
		txManager:      txManager,
		locator:        locator,
		gitCmdFactory:  gitCmdFactory,
		catfileCache:   catfileCache,
		storageManager: storageManager,
		gitOperations:  gitOperations,
		kafkaProducer:  kafkaProducer,
	}
}
